package com.ys.controller.api.finance;

import com.ys.config.MenuId;
import com.ys.entity.finance.TcwDepositPlatform;
import com.ys.entity.finance.TcwWanliFinance;
import com.ys.entity.sys.YsCol;
import com.ys.service.finance.TcwWanliFinanceService;
import com.ys.service.log.ApiLogService;
import com.ys.service.sys.CommonApiService;
import com.ys.service.sys.UploadService;
import com.ys.util.ExportExcelUtils;
import com.ys.vo.ApiResponse;
import com.ys.vo.LayuiTableVoJA;
import com.ys.vo.R;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.List;
import java.util.Map;

/**
 * 万里汇账号资金
 */
@Controller
@RequestMapping("/api/inter/tcwWanliFinance")
public class ApiInterTcwWanliFinanceController {
    private static final Logger logger = LoggerFactory.getLogger(ApiInterTcwWanliFinanceController.class);

    @Autowired
    private CommonApiService<TcwWanliFinance> commonApiService;

    @Autowired
    private TcwWanliFinanceService tcwWanliFinanceService;

    @Autowired
    private ApiLogService apiLogService;


    /**
     * 设置查询的cond的sql设置
     * @param cond
     * @return
     */
    public TcwWanliFinance setSeachSql(TcwWanliFinance cond){

        cond.addLeftJoin("TCW_DepositPlatform D ON D.Code = A.DepositPlatformCode ")//万里汇账号资金
                .addField("D.PlatformName AS platformName")//收款平台名称
                .addField("D.Code AS depositPlatformCode")//账号编码
                .addField("D.Name AS name")//账号名称
                .addField("D.Mid AS depositAccountMid")

        .addLeftJoin("TB_CompanyInfo O ON O.Vid = D.CompanyVid ")//公司信息表
                .addField("O.Vname AS vname")//公司名称

        //排序
        .setOrderby("D.Code DESC");

        cond = commonApiService.dataAuth(MenuId.TCW_WanliFinance, cond);
        return  cond;
    }


    /**
     * 查询
     */
    @RequiresPermissions("tcwWanliFinance:view")
    @RequestMapping("/search")
    @ResponseBody
    public LayuiTableVoJA search(Model model, HttpServletRequest request, HttpServletResponse response,
                                 @ModelAttribute TcwWanliFinance cond,String conditions
    ){
        try {
            cond = setSeachSql(cond);
            return commonApiService.searchLay(cond);
        }catch (Exception e){
            logger.error("查询出错：",e.getMessage(),e);
            LayuiTableVoJA tableVoJA = new LayuiTableVoJA();
            tableVoJA.setCode(1);
            tableVoJA.setMsg("查询出错，请稍后重试！");
            return tableVoJA;
        }
    }

    /**
     * 导出
     */
    @RequestMapping("/export")
    @ResponseBody
    public R export(@ModelAttribute TcwWanliFinance cond,String conditions){
        try {
            cond.setPage(0).setSize(999999);
            cond = setSeachSql(cond);
            //获取菜单字段数据
            List<YsCol> listField = new YsCol()
                    .setMenuId(MenuId.TCW_WanliFinance)
                    .setFrontShow(1)
                    .setOrderby("A.SortNo asc")
                    .queryList();
            //获取数据
            List<Map<String, Object>> listData = cond.queryMap();

            //处理数据
            ExportExcelUtils<TcwWanliFinance> util = new ExportExcelUtils<>(new TcwWanliFinance());
            String toFilePath = util.exportExcel(listData, listField, "万里汇账号资金");
            UploadService.UploadDto dto = commonApiService.uploadLocalToServer(toFilePath);
            return R.ok(dto.getUrl());
        }catch (Exception e){
            logger.error("导出出错：",e.getMessage(),e);
            return R.error("导出失败，请稍后重试！");
        }
    }



    /**
     * 新增
     */
    @RequestMapping("/toAdd")
    @ResponseBody
    public R toSave(HttpServletRequest request, @RequestParam Map<String, Object> params){
        try {
            //新增
            return tcwWanliFinanceService.add(params,MenuId.TCW_WanliFinance);
        } catch (Exception e) {
            logger.error("新增出错：",e.getMessage(),e);
            return R.error(e.getCause().getMessage());
        }
    }


    /**
     * 修改
     */
    @RequestMapping("/toEdit")
    @ResponseBody
    public R toEdit(HttpServletRequest request, @RequestParam Map<String, Object> params){
        try {
            //修改
            return tcwWanliFinanceService.update(params,MenuId.TCW_WanliFinance);
        } catch (Exception e) {
            logger.error("修改出错：",e.getMessage(),e);
            return R.error(e.getCause().getMessage());
        }
    }






    /**
     * 弹出框
     */
    @RequestMapping("/searchForModal")
    @ResponseBody
    public LayuiTableVoJA searchForModal(@ModelAttribute TcwWanliFinance cond){
        cond.setStatus(1);
        cond = setSeachSql(cond);
        return commonApiService.searchLay(cond);
    }


    /**
     * 资金对账
     */
    @RequiresPermissions("tcwWanliFinance:reconciliation")
    @RequestMapping("/reconciliation")
    @ResponseBody
    public R reconciliation(HttpServletRequest request, @RequestParam Map<String, Object> params,String subData
    ) {
        try {
            ApiResponse apiResponse = tcwWanliFinanceService.inquiryBalance();
            if (apiResponse.getCode() == 500) {
                apiLogService.addApiLog("Wanli", "inquiryBalance", "ECP_API定时获取万里汇接口查询账户余额出错，：" ,"账户:莫程" , apiResponse.getCode(), apiResponse.getMessage());
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return R.ok();
    }


}